package com.complaint.rest.dao;

import com.complaint.rest.em.EMF;
import com.complaint.rest.helper.IdHelper;
import com.complaint.rest.model.User;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 * Created by Alex
 */
public class UserDAOImpl implements UserDAO {
    private EntityManager entityManager = EMF.get().createEntityManager();

    @Override
    public User addUser(User user) {
        User persistedUser = new User(
                IdHelper.get(),
                user.getFirstName(),
                user.getLastName(),
                user.getEmail(),
                user.getPassword()
        );
        entityManager.getTransaction().begin();
        entityManager.persist(persistedUser);
        entityManager.getTransaction().commit();
        return persistedUser;
    }

    @Override
    public void removeUser(User user) {
        entityManager.getTransaction().begin();
        entityManager.remove(user);
        entityManager.getTransaction().commit();
    }

    @Override
    public void updateUser(User user) {
        entityManager.getTransaction().begin();
        entityManager.persist(user);
        entityManager.getTransaction().commit();
    }

    @Override
    public User getUser(String id) {
        return entityManager.find(User.class, id);
    }

    @Override
    public User getUserByEmail(String email) {
        Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email = :email").setParameter("email", email);
        User user = null;
        try {
            user = (User) query.getSingleResult();
        } catch (NoResultException e) {
            // TODO logging
        }
        return user;
    }
}
